package com.afdor.rws.event.channel.jedis.sharded;

import com.afdor.rws.annotation.extension.Extension;
import com.afdor.rws.event.Event;
import com.afdor.rws.event.channel.client.producer.AbstractEventProducer;
import com.afdor.rws.event.channel.client.producer.EventProducer;
import com.afdor.rws.event.channel.jedis.JedisUtils;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

/**
 * 基于ShardedJedis实现的事件生产者
 *
 * @author 悭梵
 * @date Created in 2018-08-17 18:54
 */
@Slf4j
@ToString
@EqualsAndHashCode
@Extension(value = "sharded_jedis", order = Extension.NORMAL_ORDER - 100, scope = Extension.Scope.PROTOTYPE, interfaceClass = EventProducer.class)
public class ShardedJedisEventProducer extends AbstractEventProducer {

    @Getter
    @Setter
    private ShardedJedisPool shardedJedisPool;

    public ShardedJedisEventProducer(@NonNull ShardedJedisPool shardedJedisPool) {
        this.shardedJedisPool = shardedJedisPool;
    }

    @Override
    public void doSendEvent(Event event) {
        ShardedJedis jedis = shardedJedisPool.getResource();
        try {
            jedis.rpush(JedisUtils.getQueueName(event.getEventSourceName()), getSerialization().serialize(event).toString());
        } finally {
            jedis.close();
        }
    }
}
